package com.srwl.mytx.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.ChatActivity;
import com.srwl.mytx.activity.TaskDetailActivity;
import com.srwl.mytx.activity.ConversationActivity.TaskNotifyActivity;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.Task;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TaskNotifyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final String TAG = "NotifyMessageAdapter";
    private Context context;
    private List<Message> messageList;
    private NotifyMessageInteractionListener listener;


    public TaskNotifyAdapter(Context context, List<Message> messageList, NotifyMessageInteractionListener listener) {
        this.context = context;
        this.messageList = messageList;
        this.listener = listener;
    }

    @Override
    public int getItemViewType(int position) {
        return messageList.get(position).getSubType();
    }

    @Override
    public int getItemCount() {
        return messageList.size();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View taskView = LayoutInflater.from(context).inflate(R.layout.notify_message_task_item_layout, parent, false);
        return new TaskViewHolder(taskView);
    }

    @Override
    public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
        Message notify = messageList.get(position);
        TaskViewHolder viewHolder = (TaskViewHolder) holder;
        Task task = JSONObject.parseObject(notify.getExtraData(), Task.class);
        if (task == null) {
            return;
        }

        viewHolder.tv_topicTitle.setText(task.getTitle());
        viewHolder.tv_contact.setText("联系对方");
        viewHolder.tv_date.setText(DateUtils.getTimestampString(notify.getCreated()));
        viewHolder.itemView.setOnLongClickListener(v -> {
            if (listener != null) {
                listener.onItemLongClick(notify);
            }
            return false;
        });

        viewHolder.itemView.setOnClickListener(v -> toTaskDetail(task));
        boolean isEmployer = UserProfileManager.getInstance().getLoginUserInfo().getuId().equals(task.getEmployerId());
        if (task.getEmployerId().equals(UserProfileManager.getInstance().getLoginUserInfo().getuId())) {
            //联系雇佣者
            viewHolder.tv_contact.setOnClickListener(v -> contact(task.getuId()));
        } else {
            //联系雇主
            viewHolder.tv_contact.setOnClickListener(v -> contact(task.getEmployerId()));
        }
        switch (task.getStatus()) {
            case Constant.TASK_STATUS_INIT:
                viewHolder.tv_title.setText("新任务");
                User targetUser = task.getTargetUser();
                String content;
                if (targetUser != null) {
                    content = "[" + targetUser.getUsername() + "]领取了您的悬赏任务，尽快联系对方并确认任务";
                } else {
                    content = "有人领取了您的悬赏任务，尽快联系对方并确认任务";
                }
                viewHolder.tv_content.setText(content);
                break;
            case Constant.TASK_STATUS_CONFIRM_FAIL:
                viewHolder.tv_title.setText("未通过确认");
                if (isEmployer) {
                    viewHolder.tv_content.setText("任务未获得您的确认");
                } else {
                    viewHolder.tv_content.setText("任务未获得对方的确认");
                }
                break;
            case Constant.TASK_STATUS_CONFIRM:
                viewHolder.tv_title.setText("任务已确认");
                if (isEmployer) {
                    viewHolder.tv_content.setText("您已经确认了任务，等待对方完成");
                } else {
                    viewHolder.tv_content.setText("对方已经确认任务，尽快完成任务吧");
                }
                break;
            case Constant.TASK_STATUS_EMPLOYER_CANCEL:
                viewHolder.tv_title.setText("取消任务");
                if (isEmployer) {
                    viewHolder.tv_content.setText("您已经发起取消该任务的请求,等待对方确认，如果对方在6天内没做出处理，将自动取消");
                } else {
                    viewHolder.tv_content.setText("对方发起取消任务的请求,您需要在6天内做出处理，过期未处理视为同意取消该任务");
                }
                break;

            case Constant.TASK_STATUS_EXPIRY_AUTO_CANCEL:
                viewHolder.tv_title.setText("任务自动取消");
                viewHolder.tv_content.setText("任务到期没有做出处理，已经自动取消");

                break;
            case Constant.TASK_STATUS_EMPLOYEE_CANCEL:
                viewHolder.tv_title.setText("任务结束");
                if (isEmployer) {
                    viewHolder.tv_content.setText("对方取消任务");
                } else {
                    viewHolder.tv_content.setText("您已经取消任务");

                }
                break;
            case Constant.TASK_STATUS_EMPLOYEE_REFUSE_CANCEL:
                viewHolder.tv_title.setText("任务取消已中断");
                if (isEmployer) {
                    viewHolder.tv_content.setText("对方拒绝取消该任务");
                } else {
                    viewHolder.tv_content.setText("您已经拒绝取消该任务");
                }
                break;
            case Constant.TASK_STATUS_EMPLOYEE_AGREE_CANCEL:
                viewHolder.tv_title.setText("任务结束");
                if (isEmployer) {
                    viewHolder.tv_content.setText("对方同意取消任务，任务已经取消");
                } else {
                    viewHolder.tv_content.setText("任务已经取消");
                }
                break;
            case Constant.TASK_STATUS_APPLY_FINISH_TASK:
                viewHolder.tv_title.setText("申请任务验收");
                if (isEmployer) {
                    viewHolder.tv_content.setText("对方申请任务验收，请尽快做出处理");
                } else {
                    viewHolder.tv_content.setText("任务验收中...");
                }
                break;
            case Constant.TASK_STATUS_EMPLOYER_REFUSE_FINISH_APPLY:
                viewHolder.tv_title.setText("任务验收未通过");
                if (isEmployer) {
                    viewHolder.tv_content.setText("您拒绝了任务完成申请");
                } else {
                    viewHolder.tv_content.setText("对方不同意该次任务完成申请");
                }
                break;
            case Constant.TASK_STATUS_CHECK_SUCCESS:
                viewHolder.tv_title.setText("任务已结算");
                if (isEmployer) {
                    viewHolder.tv_content.setText("任务完成，赏金已经到账至对方的账户余额");
                } else {
                    viewHolder.tv_content.setText("对方已经确认任务完成，赏金已经到账至您的账户余额");
                }
                break;
            case Constant.TASK_STATUS_EXPIRY_AUTO_FINISH:
                viewHolder.tv_title.setText("任务已结算");
                if (isEmployer) {
                    viewHolder.tv_content.setText("任务到期自动完成结算，赏金已经到账至对方的账户余额");
                } else {
                    viewHolder.tv_content.setText("任务到期自动完成结算，赏金已经到账至您的账户余额");
                }
            case Constant.TASK_STATUS_OTHER_ONE_COMPLETE:
                viewHolder.tv_title.setText("任务已结束");
                if (isEmployer) {
                    viewHolder.tv_content.setText("有人完成了任务");
                } else {
                    viewHolder.tv_content.setText("悬赏任务结束了");
                }
                break;

        }
    }

    private void toTaskDetail(Task task) {

        Intent intent = new Intent(context, TaskDetailActivity.class);
        intent.putExtra(Constant.EXTRA_INFO_TASK, task);
        intent.putExtra("getTaskInfo", true);
        ((Activity) context).startActivityForResult(intent, TaskNotifyActivity.REQUEST_CODE_TO_TASK_DETAIL);
    }


    private void contact(String targetUserId) {
        User userInfo = Helper.getInstance().queryUserInfoById(targetUserId);
        if (userInfo != null) {
            context.startActivity(new Intent(context, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, userInfo));
        } else {
            getFullUserInfo(targetUserId);
        }
    }


    private void getFullUserInfo(String userId) {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        RetrofitManager.getInstance().createRequest(UserService.class)
                .getUserInfo(userId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            // showToast(tv_customerService, getString(R.string.system_busy));
                            return;
                        }
                        JSONObject object = (JSONObject) result.getData();
                        //把用户作为临时联系人 保存在数据库
                        User userInfo = object.toJavaObject(User.class);
                        userInfo.setType(Constant.USER_TYPE_TEMP);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(userInfo);
                        context.startActivity(new Intent(context, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, userInfo));

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        // showToast(tv_customerService, getString(R.string.system_busy));
                    }
                });


    }


    public class TaskViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_title)
        TextView tv_title;
        @BindView(R.id.tv_topic_title)
        TextView tv_topicTitle;
        @BindView(R.id.tv_content)
        TextView tv_content;
        @BindView(R.id.tv_contact)
        TextView tv_contact;
        @BindView(R.id.tv_date)
        TextView tv_date;

        public TaskViewHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);

        }
    }

}
